import os

from dotenv import load_dotenv
from flasgger import Swagger
from flask import Flask, render_template
from flask_cors import *  # 导入模块
from flask_elasticsearch import FlaskElasticsearch

dotenv_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), '.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path, override=True)  # override=True: 覆写已存在的变量

from apps.core.database import db, mongo
from apps.logger.web_logger import weblog
import settings

print(settings.env_path)


def config_app(app):
    app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('SQLALCHEMY_DATABASE_URI')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = bool(int(os.getenv("SQLALCHEMY_TRACK_MODIFICATIONS")))  # 关闭对模型修改的监控
    app.config['SQLALCHEMY_BINDS'] = {
        'feild209': os.getenv('SQLALCHEMY_BINDS')
    }
    app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
    app.config['MONGO_DBNAME'] = os.getenv('MONGO_DBNAME')
    app.config['MONGO_URI'] = os.getenv('MONGO_URI')
    app.config['ELASTICSEARCH_HOST'] = os.getenv('ELASTICSEARCH_HOST')
    app.config['ES_INDEXS'] = os.getenv('ES_INDEXS')
    app.config['SPARK_USER'] = os.getenv('SPARK_USER')
    app.config['FILES_USER'] = os.getenv('FILES_USER')
    app.config['ADMIN_USER'] = os.getenv('ADMIN_USER')
    app.config['DES_DIR_BASE'] = os.getenv('DES_DIR_BASE')
    app.config['TEMP_DES_DIR_BASE'] = os.getenv('TEMP_DES_DIR_BASE')
    app.config['PULL_ONCE'] = os.getenv('PULL_ONCE')
    app.config['PULL_ROUTINE'] = os.getenv('PULL_ROUTINE')
    app.config['HOSTS'] = os.getenv('HOSTS')
    lists = os.getenv('WEB_HDFS').split(",")
    app.config['WEB_HDFS_LISTS'] = lists
    app.config['WEB_HDFS'] = lists[0]
    app.config['FIELD_USER'] = os.getenv('FIELD_USER')

    if os.getenv('ADMIN_ADMIN'):
        app.config['ADMIN_ADMIN'] = os.getenv('ADMIN_ADMIN')
    else:
        app.config['ADMIN_ADMIN'] = ""

    ELASTICSEARCH_HOSTS = [one.strip() for one in os.getenv('ELASTICSEARCH_HOST').split(",")]
    app.config['ELASTICSEARCH_HOST'] = ELASTICSEARCH_HOSTS
    app.config['JSON_AS_ASCII'] = False
    app.config["SWAGGER"] = {
        "title": "openapi",
        # 'openapi': '3.0.2',
        "headers": [
            ('Access-Control-Allow-Origin', '*'),
            ('Access-Control-Allow-Methods', "GET, POST, PUT, DELETE, OPTIONS"),
            ('Access-Control-Allow-Credentials', "true"),
        ],
    }


def my_register_blueprint(app):
    """
    蓝图的注册 使用函数包裹是为了防止循环引入的问题
    :return:
    """
    from apps.apis import api
    app.register_blueprint(api, url_prefix="/api")


app = Flask(__name__)
CORS(app, supports_credentials=True)  # 设置跨域
config_app(app)
weblog.init_app(app)
es = FlaskElasticsearch(app)
# 设置es的全局mapping,查询时需要来确认是否分词

# 通过sql转换 没有必要查询mapping
with app.app_context():
    table = app.config.get("ES_INDEXS")
    alias = '/_alias/{}'.format(table)
    results = es.transport.perform_request('GET', alias)
    i = 0
    dbcode = {}
    for key in results.keys():
        i = i + 1
        dbcode[key] = i
    weblog.info("dbcode的初始化字典为 %s" % dbcode)
    app.config['ES_DBCODE'] = dbcode
    # results = es.indices.get_mapping(index=app.config.get("ES_INDEXS"))
    # app.config['ES_MAPPING'] = results[app.config.get("ES_INDEXS")]['mappings']['properties']

db.init_app(app)
app.db = db
# mongo.init_app(app)
# app.mongo = mongo
# app.mongodb = mongo.db
my_register_blueprint(app)
Swagger(app)

print(app.url_map)


@app.route("/test_up_file")
def up_fiels():
    return render_template("upfilemul.html")
